package jjn.carl.backtrack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * @author Jiang Jining
 * @since 2023-07-24 23:43
 */
public class LeetCode40 {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        boolean[] used = new boolean[candidates.length];
        List<List<Integer>> result = new ArrayList<>();
        backtrack(candidates, target, 0, 0, result, new ArrayList<>(), used);
        return result;
    }
    
    private void backtrack(int[] candidates, int target, int sum, int startIndex, List<List<Integer>> result,
                           List<Integer> path, boolean[] used) {
        if (sum > target) {
            return;
        }
        if (sum == target) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            if (i >= 1 && candidates[i] == candidates[i - 1] && !used[i - 1]) {
                continue;
            }
            path.add(candidates[i]);
            used[i] = true;
            backtrack(candidates, target, sum + candidates[i], i + 1, result, path, used);
            path.remove(path.size() - 1);
            used[i] = false;
        }
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int totalNum = scanner.nextInt();
        int target = scanner.nextInt();
        int[] candidates = new int[totalNum];
        for (int i = 0; i < totalNum; i++) {
            candidates[i] = scanner.nextInt();
        }
        List<List<Integer>> list = new LeetCode40().combinationSum2(candidates, target);
        System.out.println(String.join(",", list.toString()));
    }
}
